<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
/**
 */

namespace Admin\Controller;
use Common\Controller\AdminbaseController;
use Common\Lib\SMS\Sms;

class PublicController extends AdminbaseController
{
    const USER_LOGIN_KEEP_TTL = 2;//延时分钟数（REDIS用户登录信息）

    private $result = array();
    private $macAddrs = array(); //所有mac地址
    private $macAddr;            //第一个mac地址

    public function _initialize()
    {
        C( S( 'sp_dynamic_config' ) );//加载动态配置
    }

    //后台登陆界面
    public function login()
    {
        $admin_id = session( 'ADMIN_ID' );
        if(!empty( $admin_id )) {//已经登录
            redirect( U( "admin/index/index" ) );
        } else {
            $site_admin_url_password = C( "SP_SITE_ADMIN_URL_PASSWORD" );
            $upw = session( "__SP_UPW__" );
            if(!empty( $site_admin_url_password ) && $upw != $site_admin_url_password) {
                redirect( __ROOT__ . "/" );
            } else {
                session( "__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__", true );
                $this->display( ":login" );
            }
        }
    }

    //发送手机验证码
    public function sendsms()
    {
        $post = I('post.');
        /* Array
            (
            [username] => admin
            [phone] => 13750088482
            )*/
        $phone = trim($post['phone']);
        $find = M('Users')->where(['user_login'=>$post['username'],'mobile'=>$phone])->find();
        if(empty($find)){//找不到对应账户记录
            $resp = ['status'=>0,'msg'=>'找不到该手机号，请核对账号和手机号！'];
        }else{
            $valid=substr(microtime(true) . rand(1, 10000), -5);//限制取5个随机数字
            $smsModel = new Sms();
            //$sendStatus = $smsModel->sms_dayu($phone, $valid,1);
            $sendStatus = $smsModel->sms_huaxin($phone, $valid,1);
            if($sendStatus){
                session('mobile_valid',['send_time'=>time(),'code'=>$valid,'isCheck'=>false]);
                $resp = ['status'=>1,'msg'=>'短信发送成功'];
            }else{
                $resp = ['status'=>0,'msg'=>'短信发送失败，请稍后再试！'];
            }
        }
        $this->ajaxReturn($resp,'JSON');
    }

    /**
     * @use          [常规注销]
     */
    public function logout()
    {
        //清除redis中的登录用户
        $redis = \Common\Lib\Redis\Redis::getInstance();
        $key = C( "REDIS_LOGIN_ADMINS_SET_KEY_PREFIX" ) . session( 'ADMIN_ID' );
        $redis->del( $key );
        session( 'ADMIN_ID', null );//清空session
        session('mobile_valid') && session('mobile_valid',null);
        redirect( __ROOT__ . "/" );
    }

    public function dologin()
    {
        $login_page_showed_success = session( "__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__" );
        if(!$login_page_showed_success) {
            $this->error( 'login error!' );
        }
        $name = I( "post.username" );
        if(empty( $name )) {
            $this->error( L( 'USERNAME_OR_EMAIL_EMPTY' ) );
        }
        $pass = I( "post.password" );
        if(empty( $pass )) {
            $this->error( L( 'PASSWORD_REQUIRED' ) );
        }
        $verrify = I( "post.verify" );
        if(empty( $verrify )) {
            $this->error( L( 'CAPTCHA_REQUIRED' ) );
        }
        //验证码
        if(!sp_check_verify_code()) {
            $this->error( L( 'CAPTCHA_NOT_RIGHT' ) );
        } else {
            $user = D( "Common/Users" );
            if(strpos( $name, "@" ) > 0) {//邮箱登陆
                $where['user_email'] = $name;
            } else {
                $where['user_login'] = $name;
            }

            $result = $user->where( $where )->find();

            if(!empty( $result ) && $result['user_type'] == 1) {
                //将用户ID存到redis里面
//                $redis = \Common\Lib\Redis\Redis::getInstance();
//                //判断该用户是否该ID是否已登录
//                $key = C( "REDIS_LOGIN_ADMINS_SET_KEY_PREFIX" ) . $result["id"];
//                //var_dump($key);die;
//                $other=['23','130'];
//                if($redis->exists($key) && !in_array($result['id'],$other)) {
//                    //如果存在，无需再次判断登录的IP、浏览器、mac地址是否一样，因为前面的session已经判断过了，如果已登录，就会在有效期内跳到主页
//                    $this->error( '登录失败，该用户已登录，请稍后再试！' );
//                }

                //校验密码
                if(sp_compare_password( $pass, $result['user_pass'] )) {

                    $role_user_model = M( "RoleUser" );

                    $role_user_join = C( 'DB_PREFIX' ) . 'role as b on a.role_id =b.id';

                    $groups = $role_user_model->alias( "a" )->join( $role_user_join )->where( array( "user_id" => $result["id"], "status" => 1 ) )->order('role_id asc')->getField( "role_id", true );

                    if($result["id"] != 1 && (empty( $groups ) || empty( $result['user_status'] ))) {
                        $this->error( L( 'USE_DISABLED' ) );
                    }

                    $ip = get_client_ip( 0, true );
                    $xian = array('1','2','4','5','9','7','11', '' );
                    if(is_array( $groups )) {
                        if(!in_array( $groups[0], $xian )) {
                            $type = false;
                            if(strpos($ip,'61.144.9')===0 || strpos($ip,'61.140.1')===0 || strpos($ip,'59.41.1')===0 || strpos($ip,'59.42.')===0 || strpos($ip,'113.65.1')===0 || strpos($ip,'219.137.')===0) {
                                $type = true;
                            };
                            if(empty( $type )) {
                                $this->error( '登录失败,请在允许的ip地址登录' );
                            }
                        }
                        session('groups_groups',$groups[0]);
                    }else{
                        if(!in_array($groups,$xian)){
                            $type=false;
                            if(strpos($ip,'61.144.9')===0 || strpos($ip,'61.140.1')===0 || strpos($ip,'59.41.1')===0 || strpos($ip,'59.42.')===0 || strpos($ip,'113.65.1')===0 || strpos($ip,'219.137.')===0){
                                $type=true;
                            };
                            if(empty( $type )) {
                                $this->error( '登录失败,请在允许的ip地址登录' );
                            }
                            session( 'groups_groups', $groups );
                        }
                    }

//                    if($groups==1 || empty($groups)){
//                        $type=false;
//                        if(strpos($ip,'119.129.')===0 || strpos($ip,'61.140.1')===0 || strpos($ip,'113.119.8')===0){
//                            $type=true;
//                        };
//                        if(empty($type)){
//                            $this->error('登录失败,请在允许的ip地址登录');
//                        }
//                        session('groups_groups',1);
//                    }
                    //登入成功页面跳转
                    session('mobile_valid') && session('mobile_valid',null);//将手机校检清空，等下次登录的时候就要重新校检
                    session( 'ADMIN_ID', $result["id"] );//用户ID写入session
                    session( 'name', $result["user_login"] );//姓名写入session

                    $ip = get_client_ip( 0, true );

                    //将用户ID存到redis里面
                    $redis = \Common\Lib\Redis\Redis::getInstance();
                    $key = C( "REDIS_LOGIN_ADMINS_SET_KEY_PREFIX" ) . $result["id"];
                    //$redis->sAdd(C("REDIS_LOGIN_ADMINS_SET_KEY"),$result["id"]);
                    $redis->hSet( $key, 'admin_id', $result["id"] );
                    $redis->hSet( $key, 'last_login_ip', $ip );
                    $redis->hSet( $key, 'last_login_http_user_agent', $_SERVER['HTTP_USER_AGENT'] );
                    $redis->hSet( $key, 'last_session_id', session_id() );
                    //设置这个key过期时间为2分钟（前台每1分钟刷新一遍redis的expire）
                    $redis->expire( $key, self::USER_LOGIN_KEEP_TTL * 60 );

                    $result['last_login_ip'] = $ip;
                    $result['last_login_time'] = date( "Y-m-d H:i:s" );
                    $user->save( $result );
                    cookie( "admin_username", $name, 3600 * 24 * 30 );
                    $this->success( L( 'LOGIN_SUCCESS' ), U( "Index/index" ) );
                } else {
                    $this->error( L( 'PASSWORD_NOT_RIGHT' ) );
                }
            } else {
                $this->error( L( 'USERNAME_NOT_EXIST' ) );
            }
        }
    }

    /**
     * @use          [判断是否要弹出短信验证模态框]
     * @author       chenxiaogang
     */
    public function checkIsLoginSms()
    {
        $username = trim(I('post.username'));
        $find = M('users')->where(['user_login'=>$username])->find();
        if(empty($find)){
            $resp = ['status'=>0,'msg'=>'没这个用户'];
        }else{
            //先校检是否要弹出（已经校检过了就不用再弹出）
            $key = 'USER_LOGIN_CHECK_SMS_'.$find['id'];
            $redis = \Common\Lib\Redis\Redis::getInstance();
            //判断是否已经验证过了（fixme:换成存在redis）
            $should_check = true;//是否要验证标识
            if($redis->exists($key)){
                //比对登录的
                $oldCheck = $redis->hGetAll($key);
                $flag1 = (get_client_ip(0,true) == $oldCheck['last_check_ip']);
                $flag2 = ($_SERVER['HTTP_USER_AGENT'] == $oldCheck['last_check_http_user_agent']);
                $flag3 = ($oldCheck['has_already_check'] == true);//是否已经检查过了
                if($flag1 && $flag2 && $flag3){
                    $should_check = false;
                }
            }
            //判断是否要重新弹出
            if($should_check){
                $findRoleIds = M('role_user')->where(['user_id'=>$find['id']])->getField('role_id',true);
                if(!empty($findRoleIds)){
                    $findRoles = M('role')->where(['id'=>['in',$findRoleIds],'name'=>['like','财务%']])->find();
                    if(!empty($findRoles)){
                        $resp = ['status'=>0,'msg'=>'该用户属于财务角色，要验证短信'];
                    }else{
                        $resp = ['status'=>0,'msg'=>'该用户不需要短信验证'];
                    }
                }else{
                    $resp = ['status'=>0,'msg'=>'没这个用户对应角色'];
                }
            }else{
                $resp = ['status'=>0,'msg'=>'已验证过了'];
            }
        }
        $this->ajaxReturn($resp,'JSON');
    }

    /**
     * @use          [验证短信验证码]
     * @author       chenxiaogang
     */
    public function check_sms()
    {
        $sms_code = I('post.code');
        $username = trim(I('post.username'));
        //找到这个管理员ID
        $find = M('users')->where(['user_login'=>$username])->find();
        if(empty($find)){
            $this->ajaxReturn(['status'=>0,'msg'=>'找不到该用户'],'JSON');
        }
        $key = 'USER_LOGIN_CHECK_SMS_'.$find['id'];
        $redis = \Common\Lib\Redis\Redis::getInstance();
        //判断是否已经验证过了
        $should_check = true;//是否要验证标识
        if($redis->exists($key)){
            //比对登录的
            $oldCheck = $redis->hGetAll($key);
            $flag1 = (get_client_ip(0,true) == $oldCheck['last_check_ip']);
            $flag2 = ($_SERVER['HTTP_USER_AGENT'] == $oldCheck['last_check_http_user_agent']);
            $flag3 = ($oldCheck['has_already_check'] == true);//是否已经检查过了
            if($flag1 && $flag2 && $flag3){
                $should_check = false;
            }
        }
        if($should_check){
            //校验短信验证码
            $cmp_mobile_valid = session('mobile_valid');
            if(is_null($cmp_mobile_valid)){
                $resp = ['status'=>0,'msg'=>'验证码过期，请重新发送'];
            }else{
                if(time()-$cmp_mobile_valid['send_time'] > 1800){
                    $resp = ['status'=>0,'msg'=>'手机验证码已过期，请重新再试'];
                }else{
                    if($sms_code == $cmp_mobile_valid['code']){
                        $resp = ['status'=>1,'msg'=>'验证成功'];
                    }else{
                        $resp = ['status'=>0,'msg'=>'您输入的短信验证码有误'];
                    }
                }
            }
            //将校检时的浏览器、IP等信息记录起来
            $save = [
                'last_check_ip'=>get_client_ip(0,true),
                'last_check_http_user_agent'=>$_SERVER['HTTP_USER_AGENT'],
                'has_already_check'=>true,//标识已经检查过了
            ];
            $redis->hMset($key,$save);
            $redis->expire($key,30*24*60*60);//缓存30天
        }else{
            $resp = ['status'=>1,'msg'=>'已验证过'];
        }
        $this->ajaxReturn($resp,'JSON');
    }
    
    public function keep_login()
    {
        //将用户ID存到redis里面
        $redis = \Common\Lib\Redis\Redis::getInstance();
        if(is_null( session( 'ADMIN_ID' ) )) {
            $resp = [ 'status' => 0, 'message' => 'session过期了' ];
        } else {
            $key = C( "REDIS_LOGIN_ADMINS_SET_KEY_PREFIX" ) . session( 'ADMIN_ID' );
            if($redis->exists( $key )) {
                //如果存在这个$key，还得校验一下session_id是否是当前登录的session_id
                if(session_id() != $redis->hGet( $key, 'last_session_id' )) {
                    $resp = [ 'status' => 0, 'message' => '该账号已由他人登录' ];
                } else {
                    //延时指定分钟
                    if($redis->expire( $key, self::USER_LOGIN_KEEP_TTL * 60 )) {
                        $resp = [ 'status' => 1, 'message' => '延时成功' ];
                    } else {
                        $resp = [ 'status' => 0, 'message' => '延时失败' ];
                    }
                }
            } else {
                $resp = [ 'status' => 0, 'message' => '登录信息过期' ];
            }
            $other=['23','130'];
            if(in_array(session( 'ADMIN_ID' ),$other)){
                $resp = [ 'status' => 1, 'message' => '延时成功' ];
            }
        }
        if(0 === $resp['status']) {
            session( 'ADMIN_ID', null );
            session('mobile_valid') && session('mobile_valid',null);
        }
        $this->ajaxReturn( $resp );
    }

}